import path from 'path';
import crypto from 'crypto';
import configTool from '../../../com/configTool';
import readFromNet from '../Util/readFromNet';
import initDB from '../Util/initDB';
import saveToFile from '../Util/saveToFile';
import readFromDisk from '../Util/readFromDisk';
import imgMD5 from '../../../img/imgMD5';
import TileUtilBing from '../../TileTool/TileUtilBing';
import readFromDB from "../Util/readFromDB";
import saveToDB from "../Util/saveToDB";

let Loading = true;
const DBName = 'BingMaps';

const BingMapUrl = 'https://ecn.t1.tiles.virtualearth.net/tiles/a{tileXYToQuadKey}.jpeg?g=100';
const tileUtilBing = new TileUtilBing();
let BingTile = {
    async init() {
        if (Loading) {
            Loading = false;
            await configTool.init();
            configTool.preservableONDB() && await initDB(DBName);
        }
    },

    async getTileFileBufferByXYZ(x: number, y: number, zoom: number) {
        const tileXYToQuadKey = tileUtilBing.tileXYToQuadKey(x, y, zoom);
        return await this.getTileFileBuffer(tileXYToQuadKey);
    },


    // 获取瓦片
    async getTileFileBuffer(tileXYToQuadKey: string) {
        await this.init();
        let err, buffer, dataSource;

        const url = BingMapUrl.replace('{tileXYToQuadKey}', tileXYToQuadKey.toString());
        const {x, y, zoom} = tileUtilBing.quadKeyToTileXY(tileXYToQuadKey);

        if (zoom < 0 || zoom > 22) {

        }

        const relativePath = `\\${zoom + 1}\\${x}\\${y}.jpeg`;
        const fileSavePath = path.join(configTool.appBasePath, `temp/fileOut/${DBName}`, relativePath);

        // 从本地文件夹中获取文件
        [err, buffer, dataSource] = await readFromDisk({fileSavePath, err, buffer, dataSource});

        // 从数据库中获取文件
        [err, buffer, dataSource] = await readFromDB({DBName, relativePath, err, buffer, dataSource});

        // 从网络获取
        [err, buffer, dataSource] = await readFromNet({
            url, headers: {}, err, buffer, dataSource
        });


        if (buffer) {
            const md5Str = crypto.createHash('md5').update(buffer).digest('hex');
            if (md5Str !== imgMD5.emptyPng && md5Str !== imgMD5.transparentPng) {
                dataSource !== 'DB' && configTool.preservableONDB() && saveToDB({DBName, relativePath, buffer}).then();
                dataSource === 'Net' && configTool.preservableONFile() && saveToFile(fileSavePath, buffer).then();
            }
        }


        return [err, buffer, dataSource];
    }
};

export default BingTile;
